package util;

import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * 差异化帮助类
 * 比较同类型的两个实体的属性差异，一般用在审计日志中
 *
 * @author wyl
 */
public class DifferentiationHelper {

    public static String diff(Object originalObj, Object newObj, String... ignoreFieldNames) throws Exception {
        if (originalObj == null || newObj == null) {
            throw new Exception("比较对象不允许为空");
        }

        Class<?> typeClass = originalObj.getClass();
        if (typeClass != newObj.getClass()) {
            throw new Exception("比较对象必须类型相同");
        }

        StringBuilder sb = new StringBuilder();
        boolean hasIgnore = ignoreFieldNames.length > 0;
        Field[] fields = typeClass.getDeclaredFields();
        for (Field f : fields) {
            f.setAccessible(true);
            String propName = f.getName();
            //进行忽略的字段不比较差异化
            if (hasIgnore && Arrays.asList(ignoreFieldNames).contains(propName)) {
                continue;
            }
            Object originalValue = f.get(originalObj);
            Object newValue = f.get(newObj);
            if (!originalValue.equals(newValue)) {
                sb.append(String.format("[%s]:[%s]=>[%s]\n", propName, originalValue, newValue));
            }
        }

        return sb.toString();
    }
}
